<template>
  <div>
    <a-card title="酒店政策管理">
      <a-form
        :model="policyForm"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        :disabled="!editing"
      >
        <a-divider orientation="left">入住与退房政策</a-divider>
        
        <a-form-item label="入住时间">
          <a-time-picker v-model:value="policyForm.checkInTime" format="HH:mm" />
          <span class="time-suffix">后</span>
        </a-form-item>
        
        <a-form-item label="退房时间">
          <a-time-picker v-model:value="policyForm.checkOutTime" format="HH:mm" />
          <span class="time-suffix">前</span>
        </a-form-item>
        
        <a-form-item label="最早预订时间">
          <a-input-number v-model:value="policyForm.minAdvanceReservation" :min="0" :max="365" />
          <span class="time-suffix">天前</span>
        </a-form-item>
        
        <a-form-item label="最晚预订时间">
          <a-input-number v-model:value="policyForm.maxAdvanceReservation" :min="0" :max="365" />
          <span class="time-suffix">天前</span>
        </a-form-item>
        
        <a-divider orientation="left">取消政策</a-divider>
        
        <a-form-item label="免费取消">
          <a-input-number v-model:value="policyForm.freeCancellationHours" :min="0" :max="72" />
          <span class="time-suffix">小时前可免费取消</span>
        </a-form-item>
        
        <a-form-item label="取消费用">
          <a-input-number v-model:value="policyForm.cancellationFeePercent" :min="0" :max="100" />
          <span class="time-suffix">% 房费</span>
        </a-form-item>
        
        <a-divider orientation="left">支付政策</a-divider>
        
        <a-form-item label="支付方式">
          <a-checkbox-group v-model:value="policyForm.paymentMethods">
            <a-checkbox value="credit">信用卡</a-checkbox>
            <a-checkbox value="debit">借记卡</a-checkbox>
            <a-checkbox value="cash">现金</a-checkbox>
            <a-checkbox value="alipay">支付宝</a-checkbox>
            <a-checkbox value="wechat">微信支付</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        
        <a-form-item label="预付款">
          <a-radio-group v-model:value="policyForm.prepaymentRequired">
            <a-radio :value="true">需要预付款</a-radio>
            <a-radio :value="false">到店支付</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item v-if="policyForm.prepaymentRequired" label="预付比例">
          <a-input-number v-model:value="policyForm.prepaymentPercent" :min="0" :max="100" />
          <span class="time-suffix">% 房费</span>
        </a-form-item>
        
        <a-divider orientation="left">其他政策</a-divider>
        
        <a-form-item label="宠物政策">
          <a-radio-group v-model:value="policyForm.petsAllowed">
            <a-radio :value="true">允许携带宠物</a-radio>
            <a-radio :value="false">不可携带宠物</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item v-if="policyForm.petsAllowed" label="宠物费用">
          <a-input-number v-model:value="policyForm.petFee" :min="0" />
          <span class="time-suffix">元/只/天</span>
        </a-form-item>
        
        <a-form-item label="儿童政策">
          <a-radio-group v-model:value="policyForm.childrenAllowed">
            <a-radio :value="true">允许儿童入住</a-radio>
            <a-radio :value="false">不允许儿童入住</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item v-if="policyForm.childrenAllowed" label="儿童年龄">
          <span>不足</span>
          <a-input-number v-model:value="policyForm.childAgeThreshold" :min="0" :max="18" style="width: 60px; margin: 0 8px;" />
          <span>岁儿童可免费入住</span>
        </a-form-item>
        
        <a-form-item label="加床政策">
          <a-radio-group v-model:value="policyForm.extraBedAllowed">
            <a-radio :value="true">允许加床</a-radio>
            <a-radio :value="false">不允许加床</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item v-if="policyForm.extraBedAllowed" label="加床费用">
          <a-input-number v-model:value="policyForm.extraBedFee" :min="0" />
          <span class="time-suffix">元/床/晚</span>
        </a-form-item>
        
      </a-form>
      
      <div style="margin-left: 16.6667%;">
        <a-button v-if="!editing" type="primary" @click="editing = true">编辑</a-button>
        <a-button v-else type="primary" @click="savePolicy" style="margin-right: 8px;">保存</a-button>
        <a-button v-if="editing" @click="cancelEdit">取消</a-button>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import dayjs, { Dayjs } from 'dayjs';
import { 
  apiGetHotelPolicy, 
  apiCreateHotelPolicy, 
  apiUpdateHotelPolicy 
} from '@/api/admin-api';
import { useHotelStore } from '@/stores/hotelStrore';

// 定义类型接口
interface PolicyData {
  id?: string;
  hotelId: string;
  checkInTime: Dayjs;
  checkOutTime: Dayjs;
  minAdvanceReservation: number;
  maxAdvanceReservation: number;
  freeCancellationHours: number;
  cancellationFeePercent: number;
  paymentMethods: string[];
  prepaymentRequired: boolean;
  prepaymentPercent: number;
  petsAllowed: boolean;
  petFee: number;
  childrenAllowed: boolean;
  childAgeThreshold: number;
  extraBedAllowed: boolean;
  extraBedFee: number;
}

// 提交数据的接口，将Dayjs类型改为string
interface SubmitPolicyData extends Omit<PolicyData, 'checkInTime' | 'checkOutTime'> {
  checkInTime: string;
  checkOutTime: string;
}

// 获取hotelStore
const hotelStore = useHotelStore();

// 编辑状态
const editing = ref(false);

// 初始空数据结构
const emptyPolicyData: PolicyData = {
  hotelId: '',
  checkInTime: dayjs('14:00', 'HH:mm'),
  checkOutTime: dayjs('12:00', 'HH:mm'),
  minAdvanceReservation: 0,
  maxAdvanceReservation: 90,
  freeCancellationHours: 24,
  cancellationFeePercent: 50,
  paymentMethods: ['credit', 'alipay', 'wechat'],
  prepaymentRequired: false,
  prepaymentPercent: 100,
  petsAllowed: false,
  petFee: 100,
  childrenAllowed: true,
  childAgeThreshold: 12,
  extraBedAllowed: true,
  extraBedFee: 200
};

// 原始数据，用于取消编辑时恢复
const originalPolicy = reactive<PolicyData>({...emptyPolicyData});

// 表单数据
const policyForm = reactive<PolicyData>({...emptyPolicyData});

// 加载酒店政策数据
async function fetchPolicyData() {
  try {
    if (!hotelStore.safeHotelId) {
      message.error('酒店ID未设置，无法加载政策信息');
      return;
    }

    const response:any = await apiGetHotelPolicy(hotelStore.safeHotelId);
    if (response && response.code === 200) {
      // 转换日期字段为dayjs对象
      const policyData = response.data;
      if (typeof policyData.checkInTime === 'string') {
        policyData.checkInTime = dayjs(policyData.checkInTime, 'HH:mm');
      }
      if (typeof policyData.checkOutTime === 'string') {
        policyData.checkOutTime = dayjs(policyData.checkOutTime, 'HH:mm');
      }
      
      Object.assign(originalPolicy, policyData);
      Object.assign(policyForm, JSON.parse(JSON.stringify(originalPolicy)));
      
      // 特殊处理dayjs对象，因为JSON.stringify会将其转为字符串
      policyForm.checkInTime = originalPolicy.checkInTime;
      policyForm.checkOutTime = originalPolicy.checkOutTime;
    }
  } catch (error) {
    message.error('加载酒店政策信息失败');
    console.error('加载酒店政策信息失败:', error);
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  console.log("PolicyManage组件挂载");
  
  try {
    // 先等待一小段时间，确保AdminLayout中的hotelStore.getHotelInfo已经执行
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 确保先获取酒店信息
    if (!hotelStore.isInitialized || !hotelStore.safeHotelId) {
      console.log("等待获取酒店信息...");
      await hotelStore.getHotelInfo();
    }
    
    console.log("当前酒店ID:", hotelStore.safeHotelId);
    
    // 在确保获取到酒店ID后再加载政策数据
    if (hotelStore.safeHotelId) {
      await fetchPolicyData();
    } else {
      console.log("错误:当前酒店ID:", hotelStore.safeHotelId);
      message.warning('未找到酒店ID，无法加载政策信息');
    }
  } catch (error) {
    console.error("PolicyManage初始化失败:", error);
    message.error('加载政策信息失败');
  }
});

// 保存政策
async function savePolicy() {
  try {
    // 确保表单数据包含酒店ID
    if (!hotelStore.safeHotelId) {
      message.error('酒店ID未设置，无法保存政策信息');
      return;
    }

    policyForm.hotelId = hotelStore.safeHotelId;
    
    // 准备提交的数据，将Dayjs对象转换为字符串
    const submitData: SubmitPolicyData = {
      ...JSON.parse(JSON.stringify(policyForm)),
      checkInTime: policyForm.checkInTime.format('HH:mm'),
      checkOutTime: policyForm.checkOutTime.format('HH:mm')
    };
    
    let response:any;
    if (originalPolicy.id) {
      // 更新现有政策信息
      response = await apiUpdateHotelPolicy(hotelStore.safeHotelId, submitData);
    } else {
      // 创建新的政策信息
      response = await apiCreateHotelPolicy(hotelStore.safeHotelId, submitData);
    }
    
    if (response && response.code === 200) {
      // 保存成功后更新原始数据
      const savedData = response.data;
      
      // 转换返回的日期字符串为dayjs对象
      if (typeof savedData.checkInTime === 'string') {
        savedData.checkInTime = dayjs(savedData.checkInTime, 'HH:mm');
      }
      if (typeof savedData.checkOutTime === 'string') {
        savedData.checkOutTime = dayjs(savedData.checkOutTime, 'HH:mm');
      }
      
      Object.assign(originalPolicy, savedData);
      
      // 深拷贝，但保留dayjs对象
      Object.assign(policyForm, JSON.parse(JSON.stringify(originalPolicy)));
      policyForm.checkInTime = originalPolicy.checkInTime;
      policyForm.checkOutTime = originalPolicy.checkOutTime;
      
      editing.value = false;
      message.success('政策信息已保存');
    } else {
      message.error(response.msg || '保存政策信息失败');
    }
  } catch (error) {
    message.error('保存政策信息失败');
    console.error('保存政策信息失败:', error);
  }
}

// 取消编辑
function cancelEdit() {
  // 恢复原始数据
  Object.assign(policyForm, JSON.parse(JSON.stringify(originalPolicy)));
  // 特殊处理dayjs对象
  policyForm.checkInTime = originalPolicy.checkInTime;
  policyForm.checkOutTime = originalPolicy.checkOutTime;
  editing.value = false;
}
</script>

<style scoped>
.time-suffix {
  margin-left: 8px;
}

:deep(.ant-divider-inner-text) {
  font-size: 16px;
  font-weight: 500;
  color: #1890ff;
}
</style> 